"""初始化基础数据脚本"""
import asyncio
import sys
import os
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import select
from db.models import User, Role, Permission, RolePermission, UserRole
from db.session import get_db
from apis.user_api import get_password_hash

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

async def init_permissions(db: AsyncSession):
    """初始化基础权限数据"""
    print("🔒 初始化基础权限数据...")
    
    permissions_data = [
        {
            "name": "用户查看",
            "code": "user:read",
            "resource": "user",
            "action": "read",
            "description": "查看用户信息"
        },
        {
            "name": "用户创建",
            "code": "user:create",
            "resource": "user",
            "action": "create",
            "description": "创建用户"
        },
        {
            "name": "用户编辑",
            "code": "user:update",
            "resource": "user",
            "action": "update",
            "description": "编辑用户信息"
        },
        {
            "name": "用户删除",
            "code": "user:delete",
            "resource": "user",
            "action": "delete",
            "description": "删除用户"
        },
        {
            "name": "角色查看",
            "code": "role:read",
            "resource": "role",
            "action": "read",
            "description": "查看角色信息"
        },
        {
            "name": "角色创建",
            "code": "role:create",
            "resource": "role",
            "action": "create",
            "description": "创建角色"
        },
        {
            "name": "角色编辑",
            "code": "role:update",
            "resource": "role",
            "action": "update",
            "description": "编辑角色信息"
        },
        {
            "name": "角色删除",
            "code": "role:delete",
            "resource": "role",
            "action": "delete",
            "description": "删除角色"
        },
        {
            "name": "权限查看",
            "code": "permission:read",
            "resource": "permission",
            "action": "read",
            "description": "查看权限信息"
        },
        {
            "name": "权限创建",
            "code": "permission:create",
            "resource": "permission",
            "action": "create",
            "description": "创建权限"
        },
        {
            "name": "权限编辑",
            "code": "permission:update",
            "resource": "permission",
            "action": "update",
            "description": "编辑权限信息"
        },
        {
            "name": "权限删除",
            "code": "permission:delete",
            "resource": "permission",
            "action": "delete",
            "description": "删除权限"
        },
        {
            "name": "组件查看",
            "code": "widget:read",
            "resource": "widget",
            "action": "read",
            "description": "查看组件信息"
        },
        {
            "name": "组件创建",
            "code": "widget:create",
            "resource": "widget",
            "action": "create",
            "description": "创建组件"
        },
        {
            "name": "组件编辑",
            "code": "widget:update",
            "resource": "widget",
            "action": "update",
            "description": "编辑组件信息"
        },
        {
            "name": "组件删除",
            "code": "widget:delete",
            "resource": "widget",
            "action": "delete",
            "description": "删除组件"
        },
        {
            "name": "系统管理",
            "code": "system:manage",
            "resource": "system",
            "action": "manage",
            "description": "系统管理权限"
        }
    ]
    
    created_permissions = []
    
    for perm_data in permissions_data:
        # 检查权限是否已存在
        result = await db.execute(select(Permission).where(Permission.code == perm_data["code"]))
        existing_perm = result.scalar_one_or_none()
        
        if not existing_perm:
            permission = Permission(**perm_data)
            db.add(permission)
            await db.commit()
            await db.refresh(permission)
            created_permissions.append(permission)
            print(f"✅ 权限创建成功: {perm_data['name']}")
        else:
            created_permissions.append(existing_perm)
            print(f"⚠️ 权限已存在: {perm_data['name']}")
    
    return created_permissions

async def init_roles(db: AsyncSession):
    """初始化基础角色数据"""
    print("\n👥 初始化基础角色数据...")
    
    roles_data = [
        {
            "name": "超级管理员",
            "code": "super_admin",
            "description": "拥有系统所有权限的最高管理员",
            "is_active": True
        },
        {
            "name": "系统管理员",
            "code": "system_admin",
            "description": "负责系统管理的管理员",
            "is_active": True
        },
        {
            "name": "用户管理员",
            "code": "user_admin",
            "description": "负责用户管理的管理员",
            "is_active": True
        },
        {
            "name": "组件管理员",
            "code": "widget_admin",
            "description": "负责组件管理的管理员",
            "is_active": True
        },
        {
            "name": "普通用户",
            "code": "normal_user",
            "description": "普通用户角色",
            "is_active": True
        }
    ]
    
    created_roles = []
    
    for role_data in roles_data:
        # 检查角色是否已存在
        result = await db.execute(select(Role).where(Role.code == role_data["code"]))
        existing_role = result.scalar_one_or_none()
        
        if not existing_role:
            role = Role(**role_data)
            db.add(role)
            await db.commit()
            await db.refresh(role)
            created_roles.append(role)
            print(f"✅ 角色创建成功: {role_data['name']}")
        else:
            created_roles.append(existing_role)
            print(f"⚠️ 角色已存在: {role_data['name']}")
    
    return created_roles

async def assign_permissions_to_roles(db: AsyncSession, permissions: list, roles: list):
    """为角色分配权限"""
    print("\n🔗 为角色分配权限...")
    
    # 获取所有权限ID
    all_permission_ids = [p.id for p in permissions]
    
    # 超级管理员获得所有权限
    super_admin = next((r for r in roles if r.code == "super_admin"), None)
    if super_admin:
        # 删除现有权限关联
        await db.execute(select(RolePermission).where(RolePermission.role_id == super_admin.id))
        
        # 添加新的权限关联
        for perm_id in all_permission_ids:
            role_permission = RolePermission(role_id=super_admin.id, permission_id=perm_id)
            db.add(role_permission)
        
        await db.commit()
        print(f"✅ 超级管理员权限分配成功，获得 {len(all_permission_ids)} 个权限")
    
    # 系统管理员获得系统管理权限
    system_admin = next((r for r in roles if r.code == "system_admin"), None)
    if system_admin:
        system_permissions = [p for p in permissions if p.resource in ["system", "user", "role", "permission"]]
        system_permission_ids = [p.id for p in system_permissions]
        
        # 删除现有权限关联
        await db.execute(select(RolePermission).where(RolePermission.role_id == system_admin.id))
        
        # 添加新的权限关联
        for perm_id in system_permission_ids:
            role_permission = RolePermission(role_id=system_admin.id, permission_id=perm_id)
            db.add(role_permission)
        
        await db.commit()
        print(f"✅ 系统管理员权限分配成功，获得 {len(system_permission_ids)} 个权限")
    
    # 用户管理员获得用户相关权限
    user_admin = next((r for r in roles if r.code == "user_admin"), None)
    if user_admin:
        user_permissions = [p for p in permissions if p.resource in ["user", "role"]]
        user_permission_ids = [p.id for p in user_permissions]
        
        # 删除现有权限关联
        await db.execute(select(RolePermission).where(RolePermission.role_id == user_admin.id))
        
        # 添加新的权限关联
        for perm_id in user_permission_ids:
            role_permission = RolePermission(role_id=user_admin.id, permission_id=perm_id)
            db.add(role_permission)
        
        await db.commit()
        print(f"✅ 用户管理员权限分配成功，获得 {len(user_permission_ids)} 个权限")
    
    # 组件管理员获得组件相关权限
    widget_admin = next((r for r in roles if r.code == "widget_admin"), None)
    if widget_admin:
        widget_permissions = [p for p in permissions if p.resource == "widget"]
        widget_permission_ids = [p.id for p in widget_permissions]
        
        # 删除现有权限关联
        await db.execute(select(RolePermission).where(RolePermission.role_id == widget_admin.id))
        
        # 添加新的权限关联
        for perm_id in widget_permission_ids:
            role_permission = RolePermission(role_id=widget_admin.id, permission_id=perm_id)
            db.add(role_permission)
        
        await db.commit()
        print(f"✅ 组件管理员权限分配成功，获得 {len(widget_permission_ids)} 个权限")
    
    # 普通用户获得查看权限
    normal_user = next((r for r in roles if r.code == "normal_user"), None)
    if normal_user:
        read_permissions = [p for p in permissions if p.action == "read"]
        read_permission_ids = [p.id for p in read_permissions]
        
        # 删除现有权限关联
        await db.execute(select(RolePermission).where(RolePermission.role_id == normal_user.id))
        
        # 添加新的权限关联
        for perm_id in read_permission_ids:
            role_permission = RolePermission(role_id=normal_user.id, permission_id=perm_id)
            db.add(role_permission)
        
        await db.commit()
        print(f"✅ 普通用户权限分配成功，获得 {len(read_permission_ids)} 个权限")

async def assign_admin_role(db: AsyncSession, roles: list):
    """为admin用户分配超级管理员角色"""
    print("\n👤 为admin用户分配超级管理员角色...")
    
    # 查找admin用户
    result = await db.execute(select(User).where(User.username == "admin"))
    admin_user = result.scalar_one_or_none()
    
    if not admin_user:
        print("⚠️ admin用户不存在，跳过角色分配")
        return
    
    # 获取超级管理员角色
    super_admin = next((r for r in roles if r.code == "super_admin"), None)
    if not super_admin:
        print("⚠️ 超级管理员角色不存在，跳过角色分配")
        return
    
    # 检查是否已分配角色
    result = await db.execute(select(UserRole).where(
        UserRole.user_id == admin_user.id,
        UserRole.role_id == super_admin.id
    ))
    existing_assignment = result.scalar_one_or_none()
    
    if not existing_assignment:
        # 分配角色
        user_role = UserRole(user_id=admin_user.id, role_id=super_admin.id)
        db.add(user_role)
        await db.commit()
        print(f"✅ admin用户已分配超级管理员角色")
    else:
        print(f"⚠️ admin用户已拥有超级管理员角色")

async def main():
    """主函数"""
    print("🚀 开始初始化基础数据...\n")
    
    # 使用现有的数据库连接
    from db.session import db_manager
    
    # 等待数据库初始化完成
    await db_manager.init_db()
    
    # 创建数据库会话
    db = await db_manager.get_session()
    try:
        # 1. 初始化权限
        permissions = await init_permissions(db)
        
        # 2. 初始化角色
        roles = await init_roles(db)
        
        # 3. 为角色分配权限
        await assign_permissions_to_roles(db, permissions, roles)
        
        # 4. 为admin用户分配超级管理员角色
        await assign_admin_role(db, roles)
        
        print("\n🎉 基础数据初始化完成！")
        print("\n📊 初始化摘要:")
        print(f"   - 权限数量: {len(permissions)}")
        print(f"   - 角色数量: {len(roles)}")
        print(f"   - admin用户已分配超级管理员角色")
        
    except Exception as e:
        print(f"\n❌ 初始化失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(main())
